/**
 * xici代理
 */
const debug = require('debug')('proxy-pool');
const cheerio = require("cheerio");
const requestAsync = require("./utils/http_util.js");
const ProxyConsts = require('./proxy_consts.js');

const URL_PROXY = "http://www.xicidaili.com/nn/";

/**
 * 获取代理
 */
async function fetchProxy() {
  let result = [];
  for(let i = 1; i <= 3; ++i) {
    let list = await fetchProxyPage(i);
    // debug("%s 获取代理列表:", "xici", list);
    result = result.concat(list);
  }
  return result;
}

/**
 * 获取某一页
 */
async function fetchProxyPage(page) {
  let url = URL_PROXY + page;
  try {
    let reqeustOpts = {
      url: url,
      timeout: 30000,
      headers: ProxyConsts.HTTP_HEADERS
    };
    let body = await requestAsync(reqeustOpts);
    let $ = cheerio.load(body, { decodeEntities: false });
    let proxy = parsePage($);
    return proxy;
  } catch (error) {
    debug("解析proxy数据:%s 出错! %s ", url, error, error.stack);
    return null;
  }
}

/**
 * 解析页面
 */
function parsePage($) {
  let result = [];
  let trs = $('#ip_list').children('tbody').find('tr').slice(1);
  let tds, ip, port, protocol, life;
  trs.each(function (i, elem) {
    tds = $(this).children('td');
    ip = tds.eq(1).text();
    port = tds.eq(2).text();
    protocol = tds.eq(5).text();
    life = parseLifeText(tds.eq(8).text());  // 秒
    if(ip && port) {
      let item = {ip, port, protocol: protocol.toLowerCase(), life, name:"xici", score:0};
      result.push(item);
    }
  });
  return result;
}

/**
 * 解析life文字
 */
function parseLifeText(text) {
  let num = parseInt(text);
  if(text.indexOf("分钟")) {
    num *= 60;
  } else if(text.indexOf("小时")) {
    num *= 3600;
  } else if(text.indexOf("天")) {
    num *= 86400;
  } else {
    console.error("位置的life时间:", text);
    num = 0;
  }
  return num;
}

exports = module.exports = {
  name: "xici",
  func: fetchProxy
};